#include <stdio.h>
#include <stdlib.h>

typedef struct Nodetop{
    int data;
    struct Nodetop *next;
 }Nodetop;
 
 typedef struct Stack{
    int cnt;
    Nodetop *top;
}Link_Stack;

Link_Stack *init_linkstack(void){
    Nodetop *nt;
    nt = (Nodetop *)malloc(sizeof(Nodetop));
    nt->data = 0;
    nt->next = 0;
    Link_Stack *ls;
    ls = (Link_Stack *)malloc(sizeof(Link_Stack));
    ls->cnt = 0;
    ls->top = nt;
    return ls;
}

// push
Link_Stack *push_linkstack(Link_Stack *ls, int value){
    if (ls == 0) return 0;
    Nodetop *temp;
    temp = (Nodetop*)malloc(sizeof(Nodetop));
    temp->data = value;
    temp->next = ls->top;
    ls->top = temp;
    ls->cnt++;
}

// pop
Nodetop *pop_linkstack(Link_Stack *ls){
    Nodetop *toppest;
    toppest = ls->top;
    if (toppest == 0){
        printf("Error, Stack is empty! \n");
    }else{
        ls->cnt--;
        ls->top = toppest->next;
    }
    return toppest;
}

// print stack
int show_linkstack(Link_Stack *ls){
    Nodetop *toppest;
    toppest = ls->top;
    if (ls->top == 0){
        printf("Error, Stack is EMPTY! \n");
        return 0;
    }
    printf("Show stack: \n");
    while(toppest != 0 && toppest->next !=0){
        printf("%d ", toppest->data);
        toppest = toppest->next;
    }
    printf("\n");
    return 0;
}

int main(void){
    Link_Stack *link_stack;
    link_stack = init_linkstack();
    printf("Link stack has been initialized! \n");

    for(int i=0; i<10; ++i){
        push_linkstack(link_stack, i);
    }
    printf("Link stack has been pushed! \n");

    show_linkstack(link_stack);

    Nodetop *tempop;
    printf("Length of stack: %d. \n", link_stack->cnt);
    for(int i=0; i<10; ++i){
        tempop = pop_linkstack(link_stack);
        printf("Length of stack: %d. Poped value: %d. \n", tempop->data, link_stack->cnt);
        free(tempop);
    }
}
